<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <title>Observer Pattern</title>
    <script src="./observer.js"></script>

    <body>
        <button id="addNewObserver">Add New Observer checkbox</button>
        <input id="mainCheckbox" type="checkbox"/>
        <div id="observersContainer"></div>        
    </body>

    <script type="text/javascript">
        var controlCheckbox = document.getElementById('mainCheckbox');
        var addBtn = document.getElementById('addNewObserver');
        var container = document.getElementById('observersContainer');

        // 给controlCheckbox扩展被观察者能力
        extend(new Subject(), controlCheckbox);

        controlCheckbox.addEventListener('click', function() {
            this.Notify(this.checked);
        });

        // 添加观察者
        addBtn.addEventListener('click', AddNewObserver);
        function AddNewObserver() {
            // 创建一个checkbox
            var check = document.createElement('input');
            check.type = 'checkbox';
            check.checked = controlCheckbox.checked;

            // 扩展观察者能力
            extend(new Observer(), check);
            check.Update = function(checked) {
                this.checked = checked;
            } 

            //添加到controlCheckbox的观察者列表中
            controlCheckbox.AddObserver(check);

            // 添加到容器区域
            container.appendChild(check);
        }
    </script>
</html>